package org.example.huawei;

import java.util.concurrent.CountDownLatch;

/**
 * @version 1.0.0
 * @author: lynn
 * @description:  CountDownLatch实现
 * @date: 2021/6/4 11:02
 */
public class OrderStartThreadCountDownLatch {
    public static void main(String[] args) {
        CountDownLatch cOne = new CountDownLatch(0); // 设置线程 1 的信号量为 0
        CountDownLatch cTwo = new CountDownLatch(1);// 设置线程 2 的信号量为 1
        CountDownLatch cThree = new CountDownLatch(1);// 设置线程 3 的信号量为 1
        Thread t1 = new Thread(new Worker(cOne,cTwo));     // 因为 cOne 为 0 ,故 t1 可以直接执行
        Thread t2 = new Thread(new Worker(cTwo,cThree));   // 线程 t1 执行完毕之后,此时的 cTwo 为 0 , t2 开始执行
        Thread t3 = new Thread(new Worker(cThree,cThree)); // 线程 t2 执行完毕,此时 cThree 为 0 , t3 开始执行
        t1.start();t2.start();t3.start();
    }
    static class Worker implements  Runnable{
        private CountDownLatch countDownLatch1;private CountDownLatch countDownLatch2;
        Worker(CountDownLatch countDownLatch1,CountDownLatch countDownLatch2){
            this.countDownLatch1=countDownLatch1;this.countDownLatch2=countDownLatch2;
        }
        @Override
        public void run() {
            try {
                countDownLatch1.await();// 当前一个线程信号量为 0 时,才执行
                System.out.println("thread start : " + Thread.currentThread().getName());
                countDownLatch2.countDown();// 后一个线程信号量减 1
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
